package bb.lanxing.lib.devices.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class FitUtils {
    public static boolean checkFitFile(File file, boolean z) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(file);
        long length = file.length();
        int i = 0;
        for (long j = 0; j < length - 2; j++) {
            i = com.garmin.fit.CRC.get16(i, (byte) fileInputStream.read());
        }
        int read = fileInputStream.read();
        int read2 = fileInputStream.read();
        fileInputStream.close();
        if (read == -1 || read2 == -1) {
            throw new IOException("Failed to read crc");
        }
        ByteBuffer allocate = ByteBuffer.allocate(2);
        allocate.order(ByteOrder.LITTLE_ENDIAN);
        allocate.put((byte) read);
        allocate.put((byte) read2);
        allocate.position(0);
        short s = allocate.getShort();
        if (z && s != i) {
            fixFitFile(file.getAbsolutePath(), (short) i);
        }
        return z || s == ((short) i);
    }

    public static void fixFitFile(String str, short s) throws IOException {
        File file = new File(str);
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rws");
        randomAccessFile.skipBytes((int) (file.length() - 2));
        randomAccessFile.write(s & 255);
        randomAccessFile.write((s & 65280) >> 8);
        randomAccessFile.close();
    }
}
